// XMLHttpRequest

// 返回一个promise
const xhr = function (config) {
  return new Promise(function (resolve, reject) {
    let xhr = new XMLHttpRequest();

    xhr.open(config.method, config.url);
    xhr.send(config.data);

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status < 300) {
          // 返回response数据，自定义格式
          resolve({
            config: config,
            data: JSON.parse(xhr.responseText),
            request: xhr,
            headers: xhr.getAllResponseHeaders(),
            status: xhr.status,
            statusText: xhr.statusText,
          });
        } else {
          reject("数据请求错误:" + xhr.statusText);
        }
      }
    };
  });
};

export default xhr;
